package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.alibaba.druid.sql.visitor.functions.If;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {

            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public String uploadBpmnFile(MultipartFile file) throws IOException {
        //进行上传文件的判断,获取文件的后缀
        String ext = FileUploadUtils.getExtension(file);
        if (!"bpmn".equals(ext)) {
            throw new BusinessException("上传的文件类型必须是bpmn");
        }
        //调用api将文件上传并返回相应的路径
        String path = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        return path;
    }

    @Override
    //贴事务注解，当执行过程抛出异常，将回滚事务
    @Transactional
    public void deploy(String info, String bpmnType, String path) throws IOException {
        //1.根据路径拿到文件
        File file = new File(SystemConfig.getProfile(), path);
        //2.调用service中的api去部署流程定义，利用addInputStream
        FileInputStream fileInputStream = new FileInputStream(file);
        Deployment deployment = repositoryService.createDeployment().addInputStream(path, fileInputStream).deploy();
        //文件部署完毕之后关闭资源，后面才能删除
        fileInputStream.close();
        //获取查询对象，获取流程定义的对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        //3.把流程图信息保存到bpmnInfo里面
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void delete(Long id) {
        //数据先查到再删除，注意顺序
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //在删除流程定义之前先获取数据
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(bpmnInfo.getDeploymentId()).singleResult();
        //1.删除bpmninfo
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //2.删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId());
        //3.删除bpmn文件（路径，文件名）
        String deploymentId = bpmnInfo.getDeploymentId();
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        //文件存在将其删除
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public InputStream readResource(String deploymentId, String type) {
        InputStream inputStream = null;
        //获取id,获取流程定义查询对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        //判断类型
        if ("xml".equals(type)) {
            //响应xml
            //第一个参数为部署id，第2个参数为资源名称
            inputStream = repositoryService.getResourceAsStream(deploymentId,processDefinition.getResourceName());
        } else {
            //响应png'
            //利用图片生成插件生成图片
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            /**
             * 参数1：根据流程定义id，获取bpmnModel
             * 参数2：高亮节点集合，传空集合
             * 参数3：高亮连线集合，传空集合
             * 参数4-6：设置字体，解决乱码问题
             */
            inputStream = generator.generateDiagram(repositoryService.getBpmnModel(processDefinition.getId()),
                    Collections.emptyList(),
                    Collections.emptyList(),
                    //解决乱码问题
                    "宋体","宋体","宋体");
        }
        return inputStream;
    }

    @Override
    public List<BpmnInfo> queryByBpmnType(String type) {
        List<BpmnInfo> bpmnInfos = bpmnInfoMapper.selectByBpmnType(type);
        return bpmnInfos;

    }
}
